//
// Created by lenovo on 25-1-31.
//
#include <queue>
#include <vector>
using namespace std;

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    explicit TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

bool Find(TreeNode* root, TreeNode* x)
{
    if(root == nullptr)
        return false;

    return root == x
        || Find(root->left, x)
        || Find(root->right, x);
}

class Solution
{
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
    {
        if(root == nullptr)
            return nullptr;

        if(root == p || root == q)
            return root;

        bool pInleft, pInright, qInleft, qInright;
        pInleft = Find(root->left, p);
        pInright = !pInleft;

        qInleft = Find(root->left, q);
        qInright = !qInleft;

        if(pInleft && qInleft)
        {
            return lowestCommonAncestor(root->left, p, q);
        }
        else if(pInright && qInright)
        {
            return lowestCommonAncestor(root->right, p, q);
        }
        else
        {
            return root;
        }
    }
};